﻿using System;
using System.Windows.Forms;
using Map_Creator.MapInfo;
using Map_Creator.XNA;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Map_Creator.Painters
{
    public class DataPainter : IPainter
    {
        public CustomDataGrid DataGrid;

        private object currentValue;

        private static SpriteFont font;

        public DataPainter(CustomDataGrid dataGrid, IServiceProvider services)
        {
            DataGrid = dataGrid;
            if (font == null)
            {
                var content = new ContentManager(services, "Content");

                font = content.Load<SpriteFont>("ProgramFont");

                //content.Dispose();
            }
        }

        public Rectangle OnMouseDown(Point position, MouseButtons buttons)
        {
            if (buttons != MouseButtons.Left) return Rectangle.Empty;

            currentValue = DataGrid[position.X, position.Y];
            currentValue = DataGrid.NextValue(currentValue);
            DataGrid[position.X, position.Y] = currentValue;
            return new Rectangle(position.X,position.Y, 1, 1);
        }

        public Rectangle OnMouseMove(Point position, MouseButtons buttons)
        {
            if (buttons != MouseButtons.Left) return Rectangle.Empty;

            DataGrid[position.X, position.Y] = currentValue;
            return new Rectangle(position.X, position.Y, 1, 1);
        }

        public Rectangle OnMouseLeave()
        {
            return Rectangle.Empty;
        }

        public Rectangle OnMouseUp()
        {
            return Rectangle.Empty;
        }

        public void OnDraw(XnaGraphics xnaGraphics, Rectangle destination)
        {
            var tileSize = DataGrid.AssociatedMap.TileSize;

            for (int i = destination.Left; i < destination.Right; i++)
            {
                for (int j = destination.Top; j < destination.Bottom; j++)
                {
                    var str = "";
                    if (DataGrid.DataType == typeof(int))
                        str = DataGrid[i, j].ToString();
                    else if (DataGrid.DataType == typeof(bool))
                    {
                        str = (bool)DataGrid[i, j] ? "O" : "X";
                    }
                    var size = font.MeasureString(str);
                    xnaGraphics.DrawString(font, str,
                                           new Vector2(i*tileSize + ((tileSize - size.X)/2),
                                                       j*tileSize + ((tileSize - size.Y)/2)), Color.Red, 0, Vector2.Zero,
                                           1, SpriteEffects.None, 0);
                }
            }
        }
    }
}